import { _decorator, Component, Node, Vec3, RigidBody, BoxCollider, PhysicsSystem, PhysicsRayResult, math } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Dice')
export class Dice extends Component {
    @property
    initialForce: Vec3 = new Vec3(0, 10, 10);

    @property
    diceCount: number = 3;

    private diceNodes: Node[] = [];
    private isRolling: boolean = true;

    onLoad() {
        // 创建地面
        const ground = new Node('Ground');
        this.node.addChild(ground);
        const groundCollider = ground.addComponent(BoxCollider);
        groundCollider.size = new Vec3(50, 1, 50); // 设置地面的大小
        ground.setPosition(0, -1, 0); // 设置地面的位置

        // 创建骰子
        for (let i = 0; i < this.diceCount; i++) {
            const dice = new Node(`Dice${i + 1}`);
            this.node.addChild(dice);
            const rigidBody = dice.addComponent(RigidBody);
            dice.addComponent(BoxCollider); // 假设骰子是立方体
            rigidBody.useGravity = true;
            this.diceNodes.push(dice);
        }
    }

    start() {
        this.rollDices();
        this.schedule(this.checkIfDiceStopped, 0.5);
    }

    rollDices() {
        this.diceNodes.forEach(dice => {
            const rigidBody = dice.getComponent(RigidBody);
            rigidBody.clearState();
            rigidBody.setLinearVelocity(new Vec3(0, 0, 0));
            rigidBody.setAngularVelocity(new Vec3(0, 0, 0));
            rigidBody.applyForce(this.initialForce);
            rigidBody.applyTorque(new Vec3(Math.random(), Math.random(), Math.random()).multiplyScalar(10));
        });
    }

    checkIfDiceStopped() {
        if (this.isRolling) {
            this.isRolling = this.diceNodes.some(dice => {
                const rigidBody = dice.getComponent(RigidBody);
                const velocity = rigidBody.getLinearVelocity();
                const angularVelocity = rigidBody.getAngularVelocity();
                return velocity.length() > 0.1 || angularVelocity.length() > 0.1;
            });

            if (!this.isRolling) {
                this.calculateDiceResults();
            }
        }
    }

    calculateDiceResults() {
        this.diceNodes.forEach(dice => {
            const upVector = new Vec3(0, 1, 0);
            let maxDot = -1;
            let faceIndex = -1;

            for (let i = 0; i < 6; i++) {
                const faceNormal = this.getFaceNormal(dice, i);
                const dotProduct = Vec3.dot(faceNormal, upVector);
                if (dotProduct > maxDot) {
                    maxDot = dotProduct;
                    faceIndex = i;
                }
            }

            console.log(`Dice: ${dice.name}, Result: ${faceIndex + 1}`);
        });
    }

    getFaceNormal(dice: Node, faceIndex: number): Vec3 {
        const normals = [
            new Vec3(0, 1, 0),  // 上面
            new Vec3(0, -1, 0), // 下面
            new Vec3(-1, 0, 0), // 左面
            new Vec3(1, 0, 0),  // 右面
            new Vec3(0, 0, 1),  // 前面
            new Vec3(0, 0, -1)  // 后面
        ];
        return normals[faceIndex];
    }
}